package cn.echo42.proxy.factory;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author DaiZhiZhou
 * @file Netty
 * @create 2020-07-30 15:43
 */

public class ProxyFactory<T> {

    private  BeforeEnhance beforeEnhance;
    private  T target;
    private  AfterEnhance afterEnhance;

    public  void setTarget(T target) {
        this.target = target;
    }

    public void setBeforeEnhance(BeforeEnhance beforeEnhance) {
        this.beforeEnhance = beforeEnhance;
    }

    public void setAfterEnhance(AfterEnhance afterEnhance) {
        this.afterEnhance = afterEnhance;
    }

    public ProxyFactory(BeforeEnhance beforeEnhance, T target, AfterEnhance afterEnhance) {
        this.beforeEnhance = beforeEnhance;
        this.target = target;
        this.afterEnhance = afterEnhance;
    }

    public ProxyFactory() {}

    public T getProxyTarget() {
        return (T) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                (Object proxy, Method method, Object[] args) -> {

                    try {
                        if (beforeEnhance != null) beforeEnhance.beforeExecute();

                        Object feedBack = method.invoke(target, args);

                        if (afterEnhance != null) afterEnhance.afterExecute();

                        return feedBack;

                    } catch (Exception exception) {
                        exception.printStackTrace();
                    } finally {

                    }
                    return null;
                }
        );
    }
}
